<template>
  <div class="admin-dashboard">
    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card user-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40"><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalUsers }}</div>
              <div class="stat-label">用户总数</div>
              <div class="stat-trend">
                <span class="trend-text">较昨日 +{{ stats.userGrowth || 0 }}</span>
                <el-icon class="trend-icon up"><ArrowUp /></el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card room-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40"><OfficeBuilding /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalRooms }}</div>
              <div class="stat-label">房间总数</div>
              <div class="stat-trend">
                <span class="trend-text">入住率 {{ stats.occupancyRate || 0 }}%</span>
                <el-icon class="trend-icon up"><TrendCharts /></el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card order-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40"><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalOrders }}</div>
              <div class="stat-label">订单总数</div>
              <div class="stat-trend">
                <span class="trend-text">本月收入 ¥{{ stats.monthlyIncome || 0 }}</span>
                <el-icon class="trend-icon up"><Wallet /></el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card repair-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40"><Tools /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.pendingRepairs }}</div>
              <div class="stat-label">待处理报修</div>
              <div class="stat-trend">
                <span class="trend-text">{{ stats.repairStatus || '正常' }}</span>
                <el-icon :class="['trend-icon', stats.pendingRepairs > 5 ? 'warning' : 'normal']">
                  <Warning v-if="stats.pendingRepairs > 5" />
                  <Check v-else />
                </el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>用户增长趋势</span>
              <el-radio-group v-model="userChartPeriod" size="small" @change="updateUserChart">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">本年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="userTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>房间占用情况</span>
              <el-button type="text" size="small" @click="refreshRoomChart">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <div ref="roomOccupancyChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>报修类型统计</span>
            </div>
          </template>
          <div ref="repairTypeChart" class="chart-container small"></div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>月度收入趋势</span>
            </div>
          </template>
          <div ref="incomeChart" class="chart-container small"></div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>宿舍楼入住率</span>
            </div>
          </template>
          <div ref="dormitoryChart" class="chart-container small"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 内容区域 -->
    <el-row :gutter="20" class="content-row">
      <el-col :span="14">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最新报修</span>
              <el-button type="text" @click="$router.push('/admin/repair-management')">
                查看更多
              </el-button>
            </div>
          </template>
          
          <el-table :data="recentRepairs" style="width: 100%" stripe>
            <el-table-column prop="repairNo" label="报修单号" width="120" />
            <el-table-column prop="dormitory" label="宿舍楼" width="80" />
            <el-table-column prop="type" label="类型" width="100" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag 
                  :type="scope.row.status === '已处理' ? 'success' : 
                         scope.row.status === '处理中' ? 'warning' : 'danger'"
                  effect="light"
                >
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="报修时间" width="120" />
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="10">
        <el-card class="quick-actions-card">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>
          
          <div class="quick-actions">
            <div class="action-item" @click="$router.push('/admin/users')">
              <div class="action-icon user">
                <el-icon size="24"><UserFilled /></el-icon>
              </div>
              <div class="action-info">
                <div class="action-title">用户管理</div>
                <div class="action-desc">管理学生账户信息</div>
              </div>
              <el-icon class="action-arrow"><ArrowRight /></el-icon>
            </div>
            
            <div class="action-item" @click="$router.push('/admin/dormitories')">
              <div class="action-icon room">
                <el-icon size="24"><OfficeBuilding /></el-icon>
              </div>
              <div class="action-info">
                <div class="action-title">宿舍管理</div>
                <div class="action-desc">管理宿舍楼和房间</div>
              </div>
              <el-icon class="action-arrow"><ArrowRight /></el-icon>
            </div>
            
            <div class="action-item" @click="$router.push('/admin/announcements')">
              <div class="action-icon announcement">
                <el-icon size="24"><Bell /></el-icon>
              </div>
              <div class="action-info">
                <div class="action-title">发布公告</div>
                <div class="action-desc">发布系统通知公告</div>
              </div>
              <el-icon class="action-arrow"><ArrowRight /></el-icon>
            </div>
            
            <div class="action-item" @click="$router.push('/admin/repair-management')">
              <div class="action-icon repair">
                <el-icon size="24"><Tools /></el-icon>
              </div>
              <div class="action-info">
                <div class="action-title">报修管理</div>
                <div class="action-desc">处理学生报修请求</div>
              </div>
              <el-icon class="action-arrow"><ArrowRight /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import request from '../../utils/request'

const stats = ref({
  totalUsers: 0,
  totalRooms: 0,
  totalOrders: 0,
  pendingRepairs: 0,
  userGrowth: 0,
  occupancyRate: 0,
  monthlyIncome: 0,
  repairStatus: '正常'
})

const recentRepairs = ref([])
const userChartPeriod = ref('month')

// 图表引用
const userTrendChart = ref(null)
const roomOccupancyChart = ref(null)
const repairTypeChart = ref(null)
const incomeChart = ref(null)
const dormitoryChart = ref(null)

// 图表实例
let userTrendChartInstance = null
let roomOccupancyChartInstance = null
let repairTypeChartInstance = null
let incomeChartInstance = null
let dormitoryChartInstance = null

const loadStats = async () => {
  try {
    // 获取用户统计
    const usersResponse = await request.get('/api/student/list')
    if (usersResponse.data.code === 200) {
      stats.value.totalUsers = usersResponse.data.data.length
      stats.value.userGrowth = Math.floor(Math.random() * 10) + 1 // 模拟增长数据
    }

    // 获取房间统计
    const roomsResponse = await request.get('/api/room/list')
    if (roomsResponse.data.code === 200) {
      const rooms = roomsResponse.data.data
      stats.value.totalRooms = rooms.length
      const occupiedRooms = rooms.filter(room => room.status === '已入住').length
      stats.value.occupancyRate = Math.round((occupiedRooms / rooms.length) * 100)
    }

    // 获取订单统计
    const ordersResponse = await request.get('/api/order/list')
    if (ordersResponse.data.code === 200) {
      const orders = ordersResponse.data.data
      stats.value.totalOrders = orders.length
      stats.value.monthlyIncome = orders.reduce((total, order) => total + (order.amount || 0), 0)
    }

    // 获取报修统计
    const repairsResponse = await request.get('/api/fix/list')
    if (repairsResponse.data.code === 200) {
      const repairs = repairsResponse.data.data
      stats.value.pendingRepairs = repairs.filter(r => r.status === '未处理').length
      stats.value.repairStatus = stats.value.pendingRepairs > 5 ? '较多' : '正常'
      recentRepairs.value = repairs.slice(0, 6).map(repair => ({
        ...repair,
        createTime: new Date(repair.createTime).toLocaleDateString()
      }))
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 初始化用户趋势图
const initUserTrendChart = () => {
  if (!userTrendChart.value) return
  
  userTrendChartInstance = echarts.init(userTrendChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '新增用户',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(64, 158, 255, 0.3)'
            }, {
              offset: 1, color: 'rgba(64, 158, 255, 0.05)'
            }]
          }
        },
        data: [12, 18, 25, 30, 28, 35, 42, 38, 45]
      }
    ]
  }
  
  userTrendChartInstance.setOption(option)
}

// 初始化房间占用图
const initRoomOccupancyChart = () => {
  if (!roomOccupancyChart.value) return
  
  roomOccupancyChartInstance = echarts.init(roomOccupancyChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: '0%'
    },
    series: [
      {
        name: '房间状态',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '45%'],
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        data: [
          { value: stats.value.totalRooms * 0.75, name: '已入住', itemStyle: { color: '#67C23A' } },
          { value: stats.value.totalRooms * 0.15, name: '预定中', itemStyle: { color: '#E6A23C' } },
          { value: stats.value.totalRooms * 0.1, name: '空闲', itemStyle: { color: '#909399' } }
        ]
      }
    ]
  }
  
  roomOccupancyChartInstance.setOption(option)
}

// 初始化报修类型图
const initRepairTypeChart = () => {
  if (!repairTypeChart.value) return
  
  repairTypeChartInstance = echarts.init(repairTypeChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['水电维修', '家具维修', '卫浴设备', '门窗维修', '其他'],
      axisLabel: {
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '报修次数',
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#F56C6C' },
            { offset: 1, color: '#FCA5A5' }
          ])
        },
        data: [15, 8, 12, 6, 4]
      }
    ]
  }
  
  repairTypeChartInstance.setOption(option)
}

// 初始化收入图表
const initIncomeChart = () => {
  if (!incomeChart.value) return
  
  incomeChartInstance = echarts.init(incomeChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '收入',
        type: 'bar',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#E6A23C' },
            { offset: 1, color: '#F7D794' }
          ])
        },
        data: [12000, 15000, 18000, 16000, 20000, 22000]
      }
    ]
  }
  
  incomeChartInstance.setOption(option)
}

// 初始化宿舍楼图表
const initDormitoryChart = () => {
  if (!dormitoryChart.value) return
  
  dormitoryChartInstance = echarts.init(dormitoryChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['东楼一', '东楼二', '西楼一', '西楼二', '南楼']
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: '入住率',
        type: 'bar',
        barWidth: '50%',
        itemStyle: {
          color: function(params) {
            const colors = ['#67C23A', '#409EFF', '#E6A23C', '#F56C6C', '#909399']
            return colors[params.dataIndex]
          }
        },
        data: [85, 92, 78, 88, 76]
      }
    ]
  }
  
  dormitoryChartInstance.setOption(option)
}

// 更新用户图表
const updateUserChart = () => {
  // 这里可以根据不同时间段加载不同数据
  initUserTrendChart()
}

// 刷新房间图表
const refreshRoomChart = () => {
  initRoomOccupancyChart()
}

// 窗口大小改变时重新调整图表
const handleResize = () => {
  userTrendChartInstance?.resize()
  roomOccupancyChartInstance?.resize()
  repairTypeChartInstance?.resize()
  incomeChartInstance?.resize()
  dormitoryChartInstance?.resize()
}

onMounted(async () => {
  await loadStats()
  
  await nextTick()
  
  // 初始化所有图表
  initUserTrendChart()
  initRoomOccupancyChart()
  initRepairTypeChart()
  initIncomeChart()
  initDormitoryChart()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})
</script>

<style scoped>
.admin-dashboard {
  padding: 0;
  background: #f5f7fa;
  min-height: 100vh;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.user-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.room-card {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.order-card {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.repair-card {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  margin-right: 20px;
  opacity: 0.9;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 12px;
  opacity: 0.8;
}

.trend-text {
  margin-right: 4px;
}

.trend-icon {
  font-size: 12px;
}

.trend-icon.up {
  color: #67C23A;
}

.trend-icon.warning {
  color: #E6A23C;
}

.trend-icon.normal {
  color: #67C23A;
}

.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.chart-container {
  height: 300px;
  width: 100%;
}

.chart-container.small {
  height: 250px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.content-row {
  margin-bottom: 20px;
}

.quick-actions-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.action-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  background: #f8f9fa;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.action-item:hover {
  background: #e3f2fd;
  border-color: #409EFF;
  transform: translateX(4px);
}

.action-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
}

.action-icon.user {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.action-icon.room {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.action-icon.announcement {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.action-icon.repair {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.action-info {
  flex: 1;
}

.action-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.action-desc {
  font-size: 12px;
  color: #909399;
}

.action-arrow {
  color: #c0c4cc;
  transition: all 0.3s ease;
}

.action-item:hover .action-arrow {
  color: #409EFF;
  transform: translateX(4px);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-row .el-col {
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .stats-row .el-col {
    margin-bottom: 15px;
  }
  
  .stat-content {
    padding: 15px;
  }
  
  .stat-value {
    font-size: 24px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .chart-container.small {
    height: 200px;
  }
}
</style> 